import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/login.vue'
import Index from '../components/index.vue'
import Home from '../components/home.vue'
import Admin from '../components/admin.vue'
import AddItem from '../components/item/addItem.vue'
import ItemSort from '../components/item/itemSort.vue'
import ItemDesc from '../components/itemDesc.vue'
import UserMember from '../components/userMember.vue'
import Email from '../components/email.vue'
import Test from '../components/test.vue'
import Cart from '../components/cart.vue'
Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/home'
  },
  {
    path:"/test",
    component:Test
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: "/home",
    name: 'home',
    component: Home
  },
  {
    name: "admin",
    path: "/admin",
    component: Admin
  },
  {
    name: "addItem",
    path: "/addItem",
    component: AddItem
  },
  {
    path: '/index',
    name: 'index',
    component: Index,
    children: [{
        path: '/itemSort',
        name: 'itemSort',
        component: ItemSort
      },
      {
        path: '/itemDesc',
        name: 'itemDesc',
        component: ItemDesc
      },
      {
        path: '/cart',
        name: 'cart',
        component: Cart
      },
      {
        path: '/userMember',
        name: 'userMember',
        component: UserMember
      },
      {
        path: "/email",
        name: "email",
        component:Email
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  //1.当用户访问登录页面,则直接放行 如果不需要执行后续操作 执行return
  if (to.path === '/login') return next()
  //2.当用户访问其他页面 需要校验是否有token
  if (to.path === '/home') return next()
  if (to.path === '/itemDesc') return next()
  if (to.path === '/itemSort') return next()
  if (to.path === "/email") return next()
  if (to.path === "/test") return next()
  let rsp = window.sessionStorage.getItem('rsp')
  //如果数据为null  则访问登录页面
  if (!rsp) return next('/login')
  //如果数据不为null 则放行
  next()
})

export default router
